package com.zhuandaonet.springjpa.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuandaonet.common.domain.resp.Resp;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.time.LocalDateTime;

/**
 * 实体类的父类
 */
@MappedSuperclass
@Getter
@Setter
public abstract class EntityImpl<R extends Resp> implements IEntity {

    private static final long serialVersionUID = 8071186856618132198L;
    /**
     * 声明主键，使用UUID生成规则
     */
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    @Column(name = "id",length = 32)
    private String id;


    @org.hibernate.annotations.CreationTimestamp
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    /**
     * 重写toString方法
     *
     * @return 字符串
     */
    @Override
    public String toString(){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        }catch (Exception e){
            return String.format("Entity of type %s with id: %s", getClass().getName(), getId());
        }
    }

    /**
     * 重写equals方法
     *
     * @param obj
     *            对象
     * @return 是否相等
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!EntityImpl.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        EntityImpl other = (EntityImpl) obj;
        return getId() != null && getId().equals(other.getId());
    }

    /**
     * 重写hashCode方法
     *
     * @return HashCode
     */
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += getId() != null ? getId().hashCode() * 31 : 0;
        return hashCode;
    }

    public abstract R toResp();
}
